package com.nav.tictactoe;

import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class HostActivity extends Activity {
	Button proceed;
	CheckBox bluetooth, wifi;
	RadioGroup hostJoin, hosts;
	EditText playerName, gameName;
	TextView gameNameCaption;
	RadioButton host, join, internet;
	ServerLister serverLister;
	Thread serverListerThread;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	// set view
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_host);
        
        // handlers
        playerName = (EditText)findViewById(R.id.PlayerName);
        gameName = (EditText)findViewById(R.id.GameName);
        gameNameCaption = (TextView)findViewById(R.id.GameNameCaption);
        bluetooth = (CheckBox)findViewById(R.id.Bluetooth);
        wifi = (CheckBox)findViewById(R.id.WIFI);
        hostJoin = (RadioGroup)findViewById(R.id.HostJoin);
        host = (RadioButton)findViewById(R.id.Host);
        join = (RadioButton)findViewById(R.id.Join);
        internet = (RadioButton)findViewById(R.id.Internet);
        hosts = (RadioGroup)findViewById(R.id.Hosts);
        hosts.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				proceed.setEnabled(true);
			}
		});
        serverLister = new ServerLister(this);
		serverListerThread = new Thread(serverLister);
        proceed = (Button)findViewById(R.id.Proceed);
        proceed.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("NewApi")
			public void onClick(View v) {
				SharedData.playerName = playerName.getText().toString();
				SharedData.gameName = gameName.getText().toString();
				switch(hostJoin.getCheckedRadioButtonId()) {
				case R.id.Host:
					try {
						SharedData.bluetooth = bluetooth.isChecked();
						SharedData.wifi = wifi.isChecked();
						Intent intent = new Intent(v.getContext(), WaitActivity.class);
						if(wifi.isChecked()) {
							SharedData.socket = new ServerSocket(Configuration.ACCEPT_PORT);
							SharedData.dtsocket = new DatagramSocket(Configuration.BROADCAST_PORT);
							SharedData.dtsocket.setBroadcast(true);
						} else if(bluetooth.isChecked()) {
//							BluetoothServerSocket socket = new BluetoothServerSocket(4444);
						}
						SharedData.myChance = true;
						startActivity(intent);
					} catch(Exception e) {
						e.printStackTrace();
						AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(v.getContext());
						dialogBuilder.setTitle("Error hosting");
						dialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
							}
						});
						dialogBuilder.setMessage(e.getMessage());
						AlertDialog alertDialog = dialogBuilder.create();
						alertDialog.show();
					}
					break;
				case R.id.Join:
					try {
						String server = serverLister.getServer(hosts.getCheckedRadioButtonId());
						String[] toks = server.split(":");
						SharedData.opponent = new Socket(toks[1], Integer.parseInt(toks[2]));
						SharedData.myChance = false;
						Intent intent = new Intent(v.getContext(), GameActivity.class);
						startActivity(intent);
					} catch(Exception e) {
						AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(v.getContext());
						dialogBuilder.setTitle("Error joining");
						dialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
							}
						});
						dialogBuilder.setMessage(e.getMessage());
						AlertDialog alertDialog = dialogBuilder.create();
						alertDialog.show();
					}
					break;
				case R.id.Internet:
					// TODO connect to the internet server
					SharedData.myChance = false;
					Intent intent = new Intent(v.getContext(), WaitActivity.class);
					startActivity(intent);
				}
			}
		});
        hostJoin.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup rg, int arg1) {
				if(rg.getCheckedRadioButtonId() == R.id.Host) {
					if(serverListerThread.isAlive())
						serverLister.stop();
					hosts.setVisibility(RadioGroup.INVISIBLE);
					gameNameCaption.setVisibility(TextView.VISIBLE);
					gameName.setVisibility(EditText.VISIBLE);
			        if(Configuration.readyForBluetooth)
			        	bluetooth.setVisibility(CheckBox.VISIBLE);
					wifi.setVisibility(CheckBox.VISIBLE);
					proceed.setEnabled(true);
					proceed.setText("Host");
				} else if(rg.getCheckedRadioButtonId() == R.id.Join) {
					if(!serverListerThread.isAlive())
						serverListerThread.start();
					if(hosts.getCheckedRadioButtonId() >= 0)
						proceed.setEnabled(true);
					else
						proceed.setEnabled(false);
					gameNameCaption.setVisibility(TextView.INVISIBLE);
					gameName.setVisibility(EditText.INVISIBLE);
					bluetooth.setVisibility(CheckBox.INVISIBLE);
					wifi.setVisibility(CheckBox.INVISIBLE);
					hosts.setVisibility(RadioGroup.VISIBLE);
					proceed.setText("Join");
				} else if(rg.getCheckedRadioButtonId() == R.id.Internet) {
					if(serverListerThread.isAlive())
						serverLister.stop();
					gameNameCaption.setVisibility(TextView.INVISIBLE);
					gameName.setVisibility(EditText.INVISIBLE);
					bluetooth.setVisibility(CheckBox.INVISIBLE);
					wifi.setVisibility(CheckBox.INVISIBLE);
					hosts.setVisibility(RadioGroup.INVISIBLE);
					proceed.setText("Login");
				}
			}
        });
        
        // initialize
        if(!Configuration.readyForInternet)
        	internet.setVisibility(RadioButton.INVISIBLE);
    	wifi.setChecked(true);
        if(!Configuration.readyForBluetooth) {
        	bluetooth.setVisibility(CheckBox.INVISIBLE);
        	wifi.setEnabled(false);
        }
        hostJoin.check(R.id.Host);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
